<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>题目练习</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="getRandomQuestion">
          随机题目
        </el-button>
      </div>

      <!-- 筛选条件 -->
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="分类">
          <el-select v-model="filterForm.categoryId" placeholder="请选择分类" clearable @change="onFilterChange">
            <el-option
              v-for="category in categories"
              :key="category.categoryId"
              :label="category.name"
              :value="category.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目类型">
          <el-select v-model="filterForm.questionType" placeholder="请选择题目类型" clearable @change="onFilterChange">
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
            <el-option label="判断题" value="judge" />
            <el-option label="简答题" value="essay" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="filterForm.difficultyLevel" placeholder="请选择难度" clearable @change="onFilterChange">
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchQuestions">搜索题目</el-button>
        </el-form-item>
      </el-form>

      <!-- 当前题目 -->
      <div v-if="currentQuestion" class="question-container">
        <el-card>
          <div slot="header" class="question-header">
            <span class="question-title">{{ currentQuestion.title }}</span>
            <div>
              <el-tag
                :type="getDifficultyType(currentQuestion.difficultyLevel)"
                size="small"
                style="margin-right: 10px"
              >
                {{ getDifficultyText(currentQuestion.difficultyLevel) }}
              </el-tag>
              <el-tag type="info" size="small">
                {{ getQuestionTypeText(currentQuestion.questionType) }}
              </el-tag>
            </div>
          </div>

          <div class="question-content">
            <p>{{ currentQuestion.content }}</p>
          </div>

          <!-- 答题区域 -->
          <div class="answer-section">
            <el-form>
              <!-- 单选题 -->
              <div v-if="isSingleChoice" class="options-container">
                <div v-if="currentQuestion.options && currentQuestion.options.length > 0">
                  <el-radio-group v-model="userAnswer">
                    <el-radio
                      v-for="option in currentQuestion.options"
                      :key="option.optionId || option.key"
                      :label="option.key"
                      class="option-item"
                    >
                      {{ option.key }}. {{ option.content }}
                    </el-radio>
                  </el-radio-group>
                </div>
                <div v-else-if="extractedOptions.length > 0">
                  <!-- 从题目内容中提取的选项 -->
                  <el-radio-group v-model="userAnswer">
                    <el-radio
                      v-for="option in extractedOptions"
                      :key="option.key"
                      :label="option.key"
                      class="option-item"
                    >
                      {{ option.key }}. {{ option.content }}
                    </el-radio>
                  </el-radio-group>
                </div>
                <div v-else class="no-options">
                  <p style="color: #f56c6c;">⚠️ 该题目暂无选项数据</p>
                  <el-input v-model="userAnswer" placeholder="请直接输入答案（A、B、C、D）" />
                </div>
              </div>

              <!-- 多选题 -->
              <div v-else-if="isMultipleChoice" class="options-container">
                <div v-if="currentQuestion.options && currentQuestion.options.length > 0">
                  <el-checkbox-group v-model="userAnswerArray">
                    <el-checkbox
                      v-for="option in currentQuestion.options"
                      :key="option.optionId || option.key"
                      :label="option.key"
                      class="option-item"
                    >
                      {{ option.key }}. {{ option.content }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-else-if="extractedOptions.length > 0">
                  <!-- 从题目内容中提取的选项 -->
                  <el-checkbox-group v-model="userAnswerArray">
                    <el-checkbox
                      v-for="option in extractedOptions"
                      :key="option.key"
                      :label="option.key"
                      class="option-item"
                    >
                      {{ option.key }}. {{ option.content }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-else class="no-options">
                  <p style="color: #f56c6c;">⚠️ 该题目暂无选项数据</p>
                  <el-input v-model="userAnswer" placeholder="请直接输入答案（如：A,C）" />
                </div>
              </div>

              <!-- 判断题 -->
              <div v-else-if="isJudgeQuestion" class="options-container">
                <el-radio-group v-model="userAnswer">
                  <el-radio label="正确" class="option-item">正确</el-radio>
                  <el-radio label="错误" class="option-item">错误</el-radio>
                </el-radio-group>
              </div>

              <!-- 简答题 -->
              <div v-else-if="isEssayQuestion" class="options-container">
                <el-input
                  v-model="userAnswer"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入您的答案..."
                />
              </div>

              <!-- 未知题型的兼容处理 -->
              <div v-else class="options-container">
                <div v-if="extractedOptions.length > 0">
                  <!-- 如果能从题目中提取选项，按选择题处理 -->
                  <p style="color: #67c23a; margin-bottom: 10px;">
                    <i class="el-icon-info"></i>
                    检测到题目类型: {{ currentQuestion.questionType }}，自动识别为选择题
                  </p>
                  <el-radio-group v-model="userAnswer">
                    <el-radio
                      v-for="option in extractedOptions"
                      :key="option.key"
                      :label="option.key"
                      class="option-item"
                    >
                      {{ option.key }}. {{ option.content }}
                    </el-radio>
                  </el-radio-group>
                </div>
                <div v-else>
                  <!-- 无法识别选项，按简答题处理 -->
                  <p style="color: #e6a23c; margin-bottom: 10px;">
                    <i class="el-icon-warning"></i>
                    题目类型: {{ currentQuestion.questionType }}，按简答题处理
                  </p>
                  <el-input
                    v-model="userAnswer"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入您的答案..."
                  />
                </div>
              </div>

              <el-form-item style="margin-top: 20px">
                <el-button type="primary" @click="submitAnswer" :disabled="!hasAnswer" :loading="submitting">
                  提交答案
                </el-button>
                <el-button @click="addToFavorites" :disabled="isFavorited" :loading="favoriting">
                  <i class="el-icon-star-on"></i>
                  {{ isFavorited ? '已收藏' : '收藏题目' }}
                </el-button>
                <el-button @click="getNextQuestion">下一题</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>

      <!-- 没有题目时的提示 -->
      <div v-else class="no-question">
        <el-empty description="暂无题目">
          <el-button type="primary" @click="getRandomQuestion">获取随机题目</el-button>
        </el-empty>
      </div>
    </el-card>

    <!-- 题目列表对话框 -->
    <el-dialog title="选择题目" :visible.sync="questionListVisible" width="80%">
      <el-table :data="questionList" @row-click="selectQuestion">
        <el-table-column prop="title" label="题目标题" />
        <el-table-column prop="questionType" label="题目类型" width="100">
          <template slot-scope="scope">
            <el-tag size="small">{{ getQuestionTypeText(scope.row.questionType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="difficultyLevel" label="难度级别" width="100">
          <template slot-scope="scope">
            <el-tag :type="getDifficultyType(scope.row.difficultyLevel)" size="small">
              {{ getDifficultyText(scope.row.difficultyLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="selectQuestion(scope.row)">
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import questionManger from '@/api/questionManger'
import categoryManger from '@/api/categoryManger'
import userAnswer from '@/api/userAnswer'
import userFavorite from '@/api/userFavorite'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      currentQuestion: null,
      userAnswer: '',
      userAnswerArray: [],
      categories: [],
      filterForm: {
        categoryId: null,
        questionType: '',
        difficultyLevel: ''
      },
      questionList: [],
      questionListVisible: false,
      isFavorited: false,
      submitting: false,
      favoriting: false,
      extractedOptions: []
    }
  },
  computed: {
    hasAnswer() {
      if (!this.currentQuestion) return false

      if (this.isMultipleChoice) {
        return this.userAnswerArray.length > 0
      } else {
        return this.userAnswer.trim() !== ''
      }
    },
    userId() {
      // 从store中获取用户ID，如果没有则使用默认值
      const userId = this.$store.getters.userId || this.$store.state.user.userId
      console.log('当前用户ID:', userId)
      return userId || 1 // 开发环境默认使用用户ID为1
    },
    isSingleChoice() {
      return this.currentQuestion && (
        this.currentQuestion.questionType === 'single' ||
        this.currentQuestion.questionType === 'single_choice'
      )
    },
    isMultipleChoice() {
      return this.currentQuestion && (
        this.currentQuestion.questionType === 'multiple' ||
        this.currentQuestion.questionType === 'multiple_choice'
      )
    },
    isJudgeQuestion() {
      return this.currentQuestion && (
        this.currentQuestion.questionType === 'judge' ||
        this.currentQuestion.questionType === 'true_false' ||
        this.currentQuestion.questionType === 'judgment'
      )
    },
    isEssayQuestion() {
      return this.currentQuestion && (
        this.currentQuestion.questionType === 'essay' ||
        this.currentQuestion.questionType === 'short_answer'
      )
    }
  },
  mounted() {
    this.getAllCategories()
    this.getRandomQuestion()
  },
  methods: {
    // 获取所有分类
    getAllCategories() {
      categoryManger.getAllCategoriesApi().then(res => {
        if (res.code === 200) {
          this.categories = res.data
        }
      }).catch(() => {
        this.$message.error('获取分类列表失败')
      })
    },

    // 获取随机题目
    getRandomQuestion() {
      questionManger.getRandomQuestionApi().then(res => {
        if (res.code === 200 && res.data) {
          this.currentQuestion = res.data
          this.resetAnswer()
          this.extractOptionsFromContent()
          this.checkFavoriteStatus()
        } else {
          this.$message.warning('暂无题目')
        }
      }).catch(() => {
        this.$message.error('获取题目失败')
      })
    },

    // 重置答案
    resetAnswer() {
      this.userAnswer = ''
      this.userAnswerArray = []
      this.extractedOptions = []
    },

    // 从题目内容中提取选项
    extractOptionsFromContent() {
      this.extractedOptions = []

      if (!this.currentQuestion || !this.currentQuestion.content) {
        return
      }

      const content = this.currentQuestion.content

      // 匹配 A. B. C. D. 格式的选项
      const optionPattern = /([A-F])[.．]\s*([^A-F]+?)(?=[A-F][.．]|$)/g
      let match
      const options = []

      while ((match = optionPattern.exec(content)) !== null) {
        options.push({
          key: match[1],
          content: match[2].trim()
        })
      }

      // 如果没有找到标准格式，尝试匹配其他格式
      if (options.length === 0) {
        // 匹配 A) B) C) D) 格式
        const pattern2 = /([A-F])\)\s*([^A-F]+?)(?=[A-F]\)|$)/g
        while ((match = pattern2.exec(content)) !== null) {
          options.push({
            key: match[1],
            content: match[2].trim()
          })
        }
      }

      // 如果没有找到选项格式，尝试匹配换行分割的选项
      if (options.length === 0) {
        const lines = content.split(/[\n\r]+/)
        const optionLines = lines.filter(line =>
          /^[A-F][.．)]\s*.+/.test(line.trim())
        )

        optionLines.forEach(line => {
          const trimmed = line.trim()
          const key = trimmed.charAt(0)
          const content = trimmed.substring(2).trim()
          if (content) {
            options.push({ key, content })
          }
        })
      }

      this.extractedOptions = options
    },

    // 获取下一题（这里简化为随机获取）
    getNextQuestion() {
      this.getRandomQuestion()
    },

    // 筛选条件变化
    onFilterChange() {
      // 可以根据筛选条件获取特定题目
    },

    // 搜索题目
    searchQuestions() {
      let promise

      if (this.filterForm.categoryId) {
        promise = questionManger.getQuestionsByCategoryApi(this.filterForm.categoryId)
      } else if (this.filterForm.difficultyLevel) {
        promise = questionManger.getQuestionsByDifficultyApi(this.filterForm.difficultyLevel)
      } else {
        this.$message.warning('请选择筛选条件')
        return
      }

      promise.then(res => {
        if (res.code === 200) {
          this.questionList = res.data
          this.questionListVisible = true
        }
      }).catch(() => {
        this.$message.error('搜索题目失败')
      })
    },

    // 选择题目
    selectQuestion(question) {
      this.currentQuestion = question
      this.resetAnswer()
      this.questionListVisible = false
      this.checkFavoriteStatus()
    },

    // 检查收藏状态
    checkFavoriteStatus() {
      if (!this.currentQuestion) return

      userFavorite.checkFavorite(this.userId, this.currentQuestion.questionId).then(res => {
        if (res.code === 200) {
          this.isFavorited = res.data
        }
      }).catch(() => {
        this.isFavorited = false
      })
    },

    // 添加到收藏夹
    addToFavorites() {
      if (!this.currentQuestion) return

      this.favoriting = true
      userFavorite.addFavorite(this.userId, this.currentQuestion.questionId).then(res => {
        if (res.code === 200) {
          this.$message.success('收藏成功')
          this.isFavorited = true
        } else {
          this.$message.error(res.message || '收藏失败')
        }
      }).catch(() => {
        this.$message.error('收藏失败')
      }).finally(() => {
        this.favoriting = false
      })
    },

    // 提交答案
    submitAnswer() {
      if (!this.hasAnswer) {
        this.$message.warning('请先填写答案')
        return
      }

      // 处理不同题型的答案格式
      let answerContent = ''
      if (this.isMultipleChoice) {
        answerContent = this.userAnswerArray.join(',')
      } else {
        answerContent = this.userAnswer
      }

      const answerData = {
        questionId: this.currentQuestion.questionId,
        answerContent: answerContent,
        userId: this.userId
      }

      console.log('提交答案数据:', answerData)
      console.log('题目信息:', this.currentQuestion)

      if (!answerData.userId) {
        this.$message.error('用户信息获取失败，请重新登录')
        return
      }

      if (!answerData.questionId) {
        this.$message.error('题目信息错误')
        return
      }

      this.submitting = true
      userAnswer.submitAnswer(answerData).then(res => {
        console.log('提交答案响应:', res)
        if (res.code === 200) {
          this.$message.success('答案提交成功')
          // 显示正确答案
          if (this.currentQuestion.correctAnswer) {
            this.$message({
              message: `正确答案：${this.currentQuestion.correctAnswer}`,
              type: 'info',
              duration: 3000
            })
          }
          // 自动跳转到下一题
          setTimeout(() => {
            this.getNextQuestion()
          }, 2000)
        } else {
          this.$message.error(res.message || '提交失败')
        }
      }).catch(error => {
        console.error('提交答案失败:', error)
        this.$message.error('提交失败，请检查网络连接')
      }).finally(() => {
        this.submitting = false
      })
    },

    // 获取题型文本
    getQuestionTypeText(type) {
      const textMap = {
        'single': '单选题',
        'single_choice': '单选题',
        'multiple': '多选题',
        'multiple_choice': '多选题',
        'judge': '判断题',
        'true_false': '判断题',
        'judgment': '判断题',
        'essay': '简答题',
        'short_answer': '简答题'
      }
      return textMap[type] || type
    },

    // 获取难度类型
    getDifficultyType(level) {
      const typeMap = {
        'easy': 'success',
        'simple': 'success',
        '简单': 'success',
        'medium': 'warning',
        'normal': 'warning',
        '中等': 'warning',
        'hard': 'danger',
        'difficult': 'danger',
        '困难': 'danger'
      }
      return typeMap[level] || 'info'
    },

    // 获取难度文本
    getDifficultyText(level) {
      const textMap = {
        'easy': '简单',
        'simple': '简单',
        'medium': '中等',
        'normal': '中等',
        'hard': '困难',
        'difficult': '困难'
      }
      return textMap[level] || level
    }
  }
}
</script>

<style scoped>
.question-container {
  margin-top: 20px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-title {
  font-size: 18px;
  font-weight: bold;
}

.question-content {
  margin: 20px 0;
  font-size: 16px;
  line-height: 1.6;
}

.answer-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.options-container {
  margin-bottom: 20px;
}

.option-item {
  display: block;
  margin-bottom: 10px;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fff;
}

.option-item:hover {
  background-color: #f0f9ff;
  border-color: #409eff;
}

.no-question {
  text-align: center;
  padding: 40px 0;
}

.demo-form-inline {
  margin-bottom: 20px;
}
</style>
